from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import ugettext_lazy as _
from com.ericyang.groupshopping.user import setting as usersetting
from com.ericyang.groupshopping.user.models import UserDetail, USER_FLAG
from django import forms

class UserDetailForm(UserCreationForm):
    nickname = forms.RegexField(label=_("Nickname"), min_length=6, max_length=30, regex=r'^\w+$',
        help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
        error_message=_("This value must contain only letters, numbers and underscores."))
    email = forms.EmailField(label=_("E-mail"), max_length=75)
    userFlag = forms.ChoiceField(label=_("user flag"), choices=USER_FLAG)
    
    class Meta:
         model = UserDetail
         fields = ("username",'nickname','email','userFlag')
    
    def clean_username(self):
        username = super(UserDetailForm, self).clean_username()
        if len(username) < usersetting.USERNAME_MIN_LENGTH:
                raise forms.ValidationError(_("Ensure this value has at least " + str(usersetting.USERNAME_MIN_LENGTH) + " characters (it has " + str(len(username)) + "). "))
        return username  
    
    def clean_password2(self):
        password2 = super(UserDetailForm, self).clean_password2()
        if len(password2) < usersetting.PASSWORD_MIN_LENGTH:
                raise forms.ValidationError(_("Ensure this value has at least " + str(usersetting.PASSWORD_MIN_LENGTH) + " characters (it has " + str(len(username)) + "). "))
        return password2      

    def save(self, commit=True):
        user = super(UserDetailForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        
        if commit:
            user.save()
        return user

class UserEditForm(forms.ModelForm):
    """
    A form that lets a user change his/her profile
    """
    nickname = forms.RegexField(label=_("Nickname"), min_length=4, max_length=30, regex=r'^\w+$',
        help_text=_("Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores)."),
        error_message=_("This value must contain only letters, numbers and underscores."))
    email = forms.EmailField(label=_("E-mail"), max_length=75)
    
    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(UserEditForm, self).__init__(*args, **kwargs)

    class Meta:
         model = UserDetail
         fields = ("nickname",'email')
         
    def save(self, commit=True):
        self.user.nickname = self.cleaned_data['nickname']
        self.user.email = self.cleaned_data['email'] 
        if commit:
            self.user.save()
        return self.user
    
class ChangePasswordForm(forms.ModelForm):
    """
    A form that lets a user change set his/her password
    """
    old_password = forms.CharField(label=_("Old password"), min_length=6, max_length=30, widget=forms.PasswordInput)
    new_password1 = forms.CharField(label=_("New password"), min_length=6, max_length=30, widget=forms.PasswordInput)
    new_password2 = forms.CharField(label=_("New password confirmation") , min_length=6, max_length=30 , widget=forms.PasswordInput)

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(ChangePasswordForm, self).__init__(*args, **kwargs)

    class Meta:
         model = UserDetail
         fields = ("old_password",)

    def clean_new_password2(self):
        password1 = self.cleaned_data.get('new_password1')
        password2 = self.cleaned_data.get('new_password2')
        if password1 and password2:
            if password1 != password2:
                raise forms.ValidationError(_("The two password fields didn't match."))
        return password2
    def clean_old_password(self):
        old_pw = self.cleaned_data.get('old_password')
        if not self.user.check_password(old_pw):
            raise forms.ValidationError(_("The old password is wrong!"))
        return old_pw

    def save(self, commit=True):
        self.user.set_password(self.cleaned_data['new_password1'])
        if commit:
            self.user.save()
        return self.user

